package dao

import (
	"fmt"
	"hong/uniapp_server/domain/user"
)

type UserDao struct {
	userSqlFields string
}

func NewUserDao() *UserDao {
	return &UserDao{
		userSqlFields: generateSqlFields(user.UserEntity{}),
	}
}

func (d *UserDao) Insert(user *user.UserEntity) (int64, error) {
	sql := "INSERT INTO users (mobile, username, wx_open_id, nickname, gender, photo, last_login_time, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
	r, err := db.Exec(sql, user.Mobile, user.Username, user.WxOpenId, user.Nickname, user.Gender, user.Photo, user.LastLoginTime, user.CreatedAt)
	if err != nil {
		return 0, err
	}
	return r.LastInsertId()
}

func (d *UserDao) UpdateByWxOpenId(wxOpenId string, user *user.UserEntity) error {
	sql := "UPDATE users SET mobile = ?, username = ?, nickname = ?, gender = ?, photo = ?, last_login_time = ?, updated_at = ? WHERE wx_open_id = ?"
	_, err := db.Exec(sql, user.Mobile, user.Username, user.Nickname, user.Gender, user.Photo, user.LastLoginTime, user.UpdatedAt, wxOpenId)
	if err != nil {
		return err
	}
	return nil
}

func (d *UserDao) GetUserByOpenId(openId string) (*user.UserEntity, error) {
	var user user.UserEntity
	sql := fmt.Sprintf("SELECT %s FROM users WHERE wx_open_id = ?", d.userSqlFields)
	row := db.QueryRow(sql, openId)
	if err := mapRowToStruct(row, &user); err != nil {
		return nil, err
	}
	return &user, nil
}